package uk.co.lunagroup.files;

import java.io.File;

import javax.swing.filechooser.FileFilter;

/**
 * . class for managing file filter for JChooseFile
 * 
 * 
 * @author robert.kowalski
 * 
 */
public class ExtensionFileFilter extends FileFilter {
	private String description;

	private String[] extensions;

	public ExtensionFileFilter(final String description, final String extension) {
		this(description, new String[] { extension });
	}

	public ExtensionFileFilter(final String description,
			final String[] extensions) {
		if (description == null) {
			this.description = extensions[0];
		} else {
			this.description = description;
		}
		this.extensions = extensions.clone();
		toLower(this.extensions);
	}

	public String[] getExtensions() {
		return extensions;
	}

	public void setExtensions(final String[] extensions) {
		this.extensions = extensions;
	}

	@Override
	public String getDescription() {
		return description;
	}

	public void setDescription(final String description) {
		this.description = description;
	}

	private void toLower(final String array[]) {
		for (int i = 0, n = array.length; i < n; i++) {
			array[i] = array[i].toLowerCase();
		}
	}

	@Override
	public boolean accept(final File file) {
		if (file.isDirectory()) {
			return true;
		} else {
			String path = file.getAbsolutePath().toLowerCase();
			for (int i = 0, n = extensions.length; i < n; i++) {
				String extension = extensions[i];
				if ((path.endsWith(extension) && ((path.charAt(path.length()
						- extension.length() - 1)) == '.'))) {
					return true;
				}
			}
		}
		return false;
	}
}
